package com.hmall.gateway.filters;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter,Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 登录校验拦截
     * @param exchange the current server exchange
     * @param chain provides a way to delegate to the next filter
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否需要做登录拦截
        if (isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }
        // 3.获取token
        List<String> headers = request.getHeaders().get("authorization");
        String token = null;
        if (headers != null && !headers.isEmpty()){
            token = headers.get(0);
        }
        // 4.检验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            // 设置响应状态码401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 认证失败，程序结束，代表拦截终止
            return response.setComplete();
        }

        // 5.在获取用户信息后保存到请求头，转发到下游微服务
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        // 6.放行
        return chain.filter(swe);
    }

    /**
     * 判断是不是不需要拦截的路径。
     * @param path
     * @return true代表是不需要拦截的路径
     */
    private boolean isExclude(String path) {

        return authProperties.getExcludePaths().stream().anyMatch(pathPattern -> antPathMatcher.match(pathPattern,path));

//        for (String pathPattern : authProperties.getExcludePaths()) {
//            //我们定义的是一种特殊规则的字符串，属于spring中的AntPathMatcher类
//            if (antPathMatcher.match(pathPattern,path)){
//                return true;
//            }
//        }
//        return false;
    }

    @Override
    public int getOrder() {
        //小于
//        public static final int ORDER = Ordered.LOWEST_PRECEDENCE;
        return 0;
    }

}
